﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Net;

namespace Lon.Util
{
    public class Log
    {
        static Socket logServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        static List<Socket> logSockets = new List<Socket>();
        public static void InitNetLog()
        {
           Thread runThread = new Thread(new ThreadStart(RxProc));
            runThread.IsBackground = true;
            runThread.Start();

        }
        static void RxProc()
        {

            try
            {
                IPEndPoint ipe
                = new IPEndPoint(IPAddress.Any, 4444);
                logServerSocket.Bind(ipe);
                logServerSocket.Listen(5);

                while (true)
                {
                    try
                    {
                       Socket clientSocket = logServerSocket.Accept();
                        lock(logSockets)
                        {
                            logSockets.Add(clientSocket);
                        }
                        
                    }
                    catch
                    {
                        
                    }
                }
            }
            catch (System.Exception ex)
            {

            }



        }
        public static void WriteToFile(String fileName,String message)
        {
           String path= Path.GetDirectoryName(fileName);
            if(!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            File.AppendAllText(fileName, DateTime.Now.ToString("YY-MM-dd HH:mm:ss")+message);
        }
        static public void WriteToNet(String message)
        {
            if (message == null) return;
            message=String.Format("[{0:yy-MM-dd HH:mm:ss}]{1}\r\n",DateTime.Now,message);
            byte[] bMessage= Encoding.Default.GetBytes(message);
            lock(logSockets)
            {
                for(int i=logSockets.Count-1;i>=0;i--)
                {
                    Socket s = logSockets[i];
                    if(s==null||s.Connected==false)
                    {
                        logSockets.RemoveAt(i);
                        return;
                    }
                    try
                    {
                        s.Send(bMessage);
                    }
                    catch (System.Exception ex)
                    {
                    	
                    }
                }
            }
        }
    }
}
